package cn.nzcong.jpress.addon.articlesync.common;

import cn.nzcong.jpress.addon.articlesync.common.Exception.SecondStepAuthException;
import cn.nzcong.jpress.addon.articlesync.common.util.DESUtil;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

public class SecondStepAuthHelper {

    private static final String SPLITER = "|";

    /**
     * 设置两步验证的cookie
     *
     * @param response
     * @param key
     * @throws Exception
     */
    public static void setCookie(HttpServletResponse response, String key){
        long now = System.currentTimeMillis();
        Cookie cookie = null;
        try {
            cookie = new Cookie(Constant.SECOND_AUTH_COOKIE_KEY, now + SPLITER + DESUtil.encrypt(now + SPLITER + key, Constant.CRYPT_KEY));
        } catch (Exception e) {
            throw new SecondStepAuthException(e, "设置cookie失败");
        }
        cookie.setPath("/");
        cookie.setHttpOnly(true);
        cookie.setMaxAge(Constant.SECOND_AUTH_COOKIE_TIME);
        response.addCookie(cookie);
    }

    /**
     * 验证两步验证的cookie
     *
     * @param cookie
     * @param key
     * @return
     * @throws Exception
     */
    public static boolean validCookie(Cookie cookie, String key) {
        if(!Constant.SECOND_AUTH_COOKIE_KEY.equals(cookie.getName())){
            return false;
        }
        // 验证格式
        String[] vals = cookie.getValue().split("\\" + SPLITER);
        if(vals.length < 2){
            return false;
        }
        if(!StringUtils.isNumeric(vals[0])){
            return false;
        }
        // 验证时间
        long start = Long.valueOf(vals[0]);
        if(System.currentTimeMillis() - start > Constant.SECOND_AUTH_COOKIE_TIME * 1000L){
            return false;
        }
        // 验证内容
        String cookieStr = null;
        try {
            cookieStr = DESUtil.decrypt(vals[1], Constant.CRYPT_KEY);
        } catch (Exception e) {
            throw new SecondStepAuthException(e, "解析cookie失败");
        }
        if(!(start + SPLITER + key).equals(cookieStr)){
            return false;
        }
        return true;
    }

}
